package com.android.clinic.app.ui.personal;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.alibaba.fastjson.JSON;
import com.android.clinic.app.ClinicApplication;
import com.android.clinic.app.R;
import com.android.clinic.app.base.BaseActivity;
import com.android.clinic.app.entity.MemberInfo;
import com.android.clinic.app.entity.UserInfo;
import com.android.clinic.app.http.HttpClient;
import com.android.clinic.app.http.base.BaseObserver;
import com.android.clinic.app.http.utils.RxObservableUtils;
import com.android.clinic.app.ui.main.MainActivity;
import com.android.clinic.app.ui.widget.UIAlertView;
import com.android.clinic.app.utils.Constants;
import com.android.clinic.app.utils.Utils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by cheng on 2018/1/29.
 * 登录
 */
public class LoginActivity extends BaseActivity {

    private EditText etMobile, etCode, etCardNumber, etPassword;
    private Button btnSend;

    private String mMobile;
    private TimeCount mTimeCount;

    private UserInfo userInfo;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        setTitleBarTitle("手机快捷登录");
        setTitleBarLeftResource(R.drawable.icon_back);
        mTimeCount = new TimeCount(60000, 1000);

        etMobile = (EditText) findViewById(R.id.et_mobile);
        etCode = (EditText) findViewById(R.id.et_code);
        etCardNumber = (EditText) findViewById(R.id.et_card_number);
        etPassword = (EditText) findViewById(R.id.et_password);
        btnSend = (Button) findViewById(R.id.btn_send_code);
    }

    @Override
    protected void widgetClick(View v) {
        super.widgetClick(v);
        switch (v.getId()) {
            // 发送短信验证码
            case R.id.btn_send_code:
                if (btnSend.getText().toString().equals("重新验证")) {
                    etCode.setText("");
                }
                getVerifyCode();
                break;
            // 登录
            case R.id.btn_login:
                hideKeyboard();
                login();
                break;
            // 协议
            case R.id.layout_protocol:
                startActivity(new Intent(this, WebViewActivity.class).putExtra("path", Constants.PROTOCOL_URL));
                break;
            // 申请购卡
            case R.id.tv_buy_card:
                startActivity(new Intent(this, BuyMemberCardActivity.class));
                break;
            // 忘记密码
            case R.id.tv_find_password:
                startActivity(new Intent(this, FindPasswordActivity.class));
                break;
            default:break;
        }
    }

    /**
     * 获取验证码
     */
    private void getVerifyCode() {
        mMobile = etMobile.getText().toString().trim();
        if (Utils.isEmpty(mMobile)) {
            showToast("手机号不能为空!");
            return;
        } else if (!Utils.matchPhone(mMobile)) {
            showToast("请输入正确的手机号!");
            return;
        }
        HttpClient.getHttpService().getSmsCode(mMobile)
                .compose(this.bindToLifecycle())
                .compose(RxObservableUtils.applySchedulers())
                .subscribe(new BaseObserver<String>() {
                    @Override
                    public void onSuccess(String s) {
                        showToast("验证信息已发送您手机!");
                        mTimeCount.start();
                    }

                    @Override
                    public void onFailure(String message) {
                        showToast(message);
                    }
                });

    }

    /**
     * 登录
     */
    private void login() {
        String code = etCode.getText().toString().trim();
        String cardNumber = etCardNumber.getText().toString().trim();
        String cardPassword = etPassword.getText().toString().trim().toUpperCase();
        if (Utils.isEmpty(code)) {
            showToast("请输入手机收到的验证码!");
            return;
        } else if (Utils.isEmpty(cardNumber)) {
            showToast("卡号不能为空!");
            return;
        } else if (Utils.isEmpty(cardPassword)) {
            showToast("密码不能为空!");
            return;
        }
        /*HttpClient.getHttpService().login(mMobile, code, cardNumber, cardPassword)
                .compose(this.bindToLifecycle())
                .compose(RxObservableUtils.applySchedulers(loading, "登录中..."))
                .subscribe(new BaseObserver<UserInfo>() {
                    @Override
                    public void onSuccess(UserInfo userInfo) {
                        ClinicApplication.saveUserInfo(userInfo);
                        angoraLogin(userInfo.getId());
                        startActivity(new Intent(LoginActivity.this, MainActivity.class));
                        finish();
                    }

                    @Override
                    public void onFailure(String message) {
                        showToast(message);
                    }
                });*/
        showDialog("登录中...");
        Call<ResponseBody> loginCall = HttpClient.getHttpService().login(mMobile, code, cardNumber, cardPassword);
        loginCall.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                dismissDialog();
                try {
                    String result = response.body().string();
                    JSONObject json = new JSONObject(result);
                    String code = json.getString("code");
                    String message = json.getString("message");
                   switch (code) {
                       // 登录成功
                       case Constants.HTTP_SUCCESS:
                           userInfo = JSON.parseObject(json.getJSONObject("data").toString(), UserInfo.class);
                           MemberInfo memberInfo = JSON.parseObject(json.getJSONObject("member").toString(), MemberInfo.class);
                           angoraLogin(userInfo.getId());
                           // 0:永久用户;1:续费用户
                           if (memberInfo.getAlwaysFree() == 1) {
                               userInfo.setAlwaysFree(memberInfo.getAlwaysFree());
                               userInfo.setDueDate(memberInfo.getDueDate());
                           }
                           ClinicApplication.saveUserInfo(userInfo);
                           startActivity(new Intent(LoginActivity.this, MainActivity.class));
                           finish();
                           break;
                       // 登录失败
                       case Constants.HTTP_ERROR:
                           showToast(message);
                           break;
                       // 会员过期
                       case Constants.HTTP_MEMBER_EXPIRED:
                           userInfo = JSON.parseObject(json.getJSONObject("data").toString(), UserInfo.class);
                           ClinicApplication.saveUserInfo(userInfo);
                           memberExpired(message);
                           break;
                   }

                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                dismissDialog();
                showToast("登录失败!");
            }
        });
    }

    /**
     * 会员续费
     * @param message
     */
    private void memberExpired(String message) {
        UIAlertView.alertDialog(LoginActivity.this, "操作提示",
                message, new UIAlertView.OnThemeDialogListener() {
                    @Override
                    public void OnDismissButton() {

                    }
                    @Override
                    public void OnSureButton() {
                         startActivity(new Intent(LoginActivity.this, RenewalFeeMemberActivity.class));
                    }
                }, "去续费", "取消");
    }

    /* 定义一个倒计时的内部类 */
    private class TimeCount extends CountDownTimer {
        private TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);// 参数依次为总时长,和计时的时间间隔
        }

        @Override
        public void onFinish() {// 计时完毕时触发
            btnSend.setText("重新验证");
            btnSend.setClickable(true);
        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程显示
            btnSend.setClickable(false);
            btnSend.setText(millisUntilFinished / 1000 + "秒");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mTimeCount){
            mTimeCount.cancel();
        }
    }
}
